"""
在线词典 ： 服务端逻辑处理
"""
from socket import *
from multiprocessing import Process
from dict_db import *


# 自定义进程类做事情
class Handle(Process):
    def __init__(self, conn):
        self.conn = conn
        self.user_id = 0  # 记录登录用户的ｉｄ
        self.db = DictData()  # 数据库处理对象
        super().__init__()

    # 总分结构：总体接收请求，分情况讨论
    def run(self):
        while True:
            request = self.conn.recv(128)
            tmp = request.decode().split('\t')  # 简单解析
            # 分情况讨论
            if not request or request == b"E":
                break
            elif tmp[0] == 'R':
                # tmp-> [R,name,passwd]
                self.do_register(tmp[1], tmp[2])
            elif tmp[0] == 'L':
                # tmp-> [L,name,passwd]
                self.do_login(tmp[1], tmp[2])
            elif tmp[0] == 'Q':
                # tmp-> [Q,word]
                self.do_query(tmp[1])
            elif tmp[0] == 'H':
                # tmp-> [H]
                self.do_hist()
        self.db.close()
        self.conn.close()

    # 处理注册
    def do_register(self, name, passwd):
        # 调用数据库方法-》得到bool
        if self.db.register(name, passwd):
            self.conn.send(b"T")
        else:
            self.conn.send(b"F")

    # 处理登录
    def do_login(self, name, passwd):
        # 调用数据库方法-》(id,)  None
        res = self.db.login(name, passwd)
        if res:
            self.conn.send(b"T")
            self.user_id = res[0]
        else:
            self.conn.send(b"F")

    # 处理单词查询
    def do_query(self, word):
        # data : # (id,mean) None
        data = self.db.query(word)
        if data:
            res = "T\t" + data[1]
            self.conn.send(res.encode())
            self.db.insert_hist(self.user_id, data[0])  # 插入历史记录
        else:
            self.conn.send(b"F")

    # 历史记录
    def do_hist(self):
        # ((name,word,time),()..) ()
        data = self.db.hist(self.user_id)
        if data:
            res = "T\t"
            for row in data:
                res += "%s,%s,%s;" % row  # (name,word,time)
            self.conn.send(res.encode())
        else:
            self.conn.send(b"F")


# 开启网络
class DICTServer:
    def __init__(self, host="", port=0):
        self.host = host
        self.port = port
        self.address = (host, port)
        self.sock = self._create_socket()

    # 创建tcp套接字
    def _create_socket(self):
        sock = socket()
        sock.bind(self.address)
        return sock

    # 启动服务函数
    def serve_forever(self):
        self.sock.listen(5)
        print("Listen the port %d" % self.port)
        # 循环连接客户端
        while True:
            conn, addr = self.sock.accept()
            print("Connect from", addr)
            # 自定义进程类创建进程
            p = Handle(conn)
            p.start()


if __name__ == '__main__':
    dict = DICTServer(host="0.0.0.0", port=8887)
    dict.serve_forever()  # 启动服务
